package com.zretc.support.controller;

import com.zretc.support.entity.*;
import com.zretc.support.service.AnswerService;
import com.zretc.support.service.ExamPaperService;
import com.zretc.support.service.ExamService;
import com.zretc.support.service.ScoreService;
import com.zretc.support.tool.AjaxResponse;
import com.zretc.support.tool.ApiResultHandler;
import com.zretc.support.tool.PageData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("api")
public class ExamController {
    @Autowired
    ExamService examService;
    @Autowired
    ExamPaperService epsi;
    @Autowired
    AnswerService asi;
    @Autowired
    ScoreService ssi;

    Logger logger = LoggerFactory.getLogger(ExamController.class);

    /**
     * 分页+模糊查询
     * @param page
     * @param size
     * @param keywords
     * @return
     */
    @RequestMapping("/exams/page")
    public PageData<Exam> getByPage(@RequestParam(value = "page",defaultValue = "1") int page,
                                    @RequestParam(value = "size",defaultValue = "5") int size,
                                    @RequestParam(value = "keywords",defaultValue = "") String keywords){
        if (page==0){
            page = 1;
        }
        Page<Exam> list = examService.getExamByPage(keywords,(page-1),size);
        PageData<Exam> pageData = new PageData<>();
        // 获得数据总数
        pageData.setRecords(list.getContent());
        //当前页数
        pageData.setSize(list.getSize());

        //共几条数据
        pageData.setTotal((int)list.getTotalElements());
        pageData.setCurrent(list.getNumber());

        pageData.setMsg("请求成功！");
        return pageData;
    }

    /**
     * 添加
     * @param exam
     * @return
     */
    @PostMapping(value = "/exam/add/{begin}",produces = "application/json;charset=utf-8")
    public AjaxResponse addExam(@RequestBody Exam exam,@PathVariable("begin") Date begin){
        logger.info("begin:"+begin);
        exam.setExamBegin(begin);
        logger.info("exam:"+exam.getExamTime());
        int flag = examService.addExam(exam);
        String msg = "添加失败！";
        if (flag==1){
            msg = "添加成功！";
        }
        AjaxResponse ajaxResponse = new AjaxResponse(msg,200);
        return ajaxResponse;
    }

    /**
     * 修改
     * @param exam
     * @return
     */
    @PostMapping(value = "/exam/upd/{begin}",produces = "application/json;charset=utf-8")
    public AjaxResponse upd(@RequestBody Exam exam,@PathVariable("begin") Date begin){
        exam.setExamBegin(begin);
        int flag = examService.updateExam(exam);
        String msg = "修改失败！";
        if (flag==1){
            msg = "修改成功！";
        }
        AjaxResponse ajaxResponse = new AjaxResponse(msg,200);
        return ajaxResponse;
    }

    /**
     * 删除
     * @param examId
     * @return
     */
    @GetMapping("/exam/{examId}")
    public AjaxResponse deleteById(@PathVariable("examId") long examId){
        int flag = examService.deleteExam(examId);
        String msg = "删除失败！";
        if (flag==1){
            msg = "删除成功！";
        }

        AjaxResponse ajaxResponse = new AjaxResponse(msg,200);
        return ajaxResponse;
    }

    /**
     * 根据试卷id查找试卷信息
     * @param examCode
     * @return
     */
    @RequestMapping("/examId/{examCode}")
    public ApiResult findById(@PathVariable("examCode") long examCode){

        Exam res = examService.getExamById(examCode);
        if(res == null) {
            return ApiResultHandler.buildApiResult(10000,"考试编号不存在",null);
        }
        return ApiResultHandler.buildApiResult(200,"请求成功！",res);
    }

    /**
     * 前台 学生 我的考试 考试信息 分页
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "/getExamsByUserId", produces = "application/json;charset=utf-8")
    public PageData<Exam> getExamsByUserId(@RequestParam(value = "studentId", defaultValue = "") String studentId,@RequestParam(value = "keywords", defaultValue = "") String keywords, @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "6") int limit) {
        Page<Exam> pd = examService.getExamsByUserId(studentId,keywords,page, limit);
        PageData<Exam> pageData = new PageData<Exam>();
        pageData.setRecords(pd.getContent());
        pageData.setCode(0);
        pageData.setTotal((int) pd.getTotalElements());
        pageData.setSize(pd.getSize());
        pageData.setCurrent(pd.getNumber() + 1);
        pageData.setMsg("");
        System.out.println(pd.getContent());
        return pageData;
    }

    /**
     * 根据 paperId 获取 所有试题信息
     *
     * @param paperId
     * @return
     */
    @GetMapping(value = "/getTopicsByPaperId/{paperId}")
    public Map<Integer, Object> getTopicsByPaperId(@PathVariable("paperId") int paperId) {
        return epsi.getTopicsByPaperId(paperId);
    }

    /**
     * 根据 paperId 获取 某同学 某份试卷的所有试题信息
     *
     * @param paperId
     * @return
     */
    @GetMapping(value = "/getTopicsAndAnswers/{paperId}/{userId}/{examId}")
    public Map<Integer, Object> getTopicsAndAnswers(@PathVariable("paperId") int paperId, @PathVariable("userId") String userId, @PathVariable("examId") int examId) {
        return epsi.getTopicsAndAnswers(paperId, userId, examId);
    }

    /**
     * 添加答题表+批改客观题
     *
     * @param map
     * @param userId
     * @param examId
     * @param paperId
     */

    @PostMapping(value = "/score/{userId}/{examId}/{paperId}")
    public AjaxResponse getScore(@RequestBody Map<String, List<Object>> map, @PathVariable("userId") String userId, @PathVariable("examId") Integer examId, @PathVariable("paperId") Integer paperId) {

        //根据paperId获得1-3题目
        Map<Integer, List<Topicsingle>> map1 = epsi.getTopicsByPaperId1(paperId);
        //根据paperId获得4-5题目
        Map<Integer, List<Topicmult>> map2 = epsi.getTopicsByPaperId2(paperId);

        //客观题分数
        double s = 0.0;

        //单选题4
        for (int j = 0; j < map2.get(4).size(); j++) {
            double s1 = 0.0;
            double score = 0.0;
            //题目编号
            String topicId = map2.get(4).get(j).getChooseId();
            //正确答案
            String topicAnswer = map2.get(4).get(j).getChooseRight();
            String a = null;
            if (j < map.get("4").size()) {
                //学生答案
                a = map.get("4").get(j) + "";
                if ("1".equals(a)) {
                    a = "A";
                } else if ("2".equals(a)) {
                    a = "B";
                } else if ("3".equals(a)) {
                    a = "C";
                } else if ("4".equals(a)) {
                    a = "D";
                }
                //分数
                score = map2.get(4).get(j).getChooseScore();
                if (topicAnswer.equals(a)) {
                    s1 = score;
                    s += s1;
                }
            }

            //存入
            Answer answer = new Answer();
            answer.setUserId(userId);
            answer.setExamId(examId);
            answer.setTopicId(topicId);
            answer.setSocre(s1);
            answer.setAnswerContent(a);
            asi.addAnswer(answer);
        }

        //多选题5
        for (int j = 0; j < map2.get(5).size(); j++) {
            double s2 = 0.0;
            String a = null;
            //题目编号
            String topicId = map2.get(5).get(j).getChooseId();
            //正确答案
            String topicAnswer = map2.get(5).get(j).getChooseRight();
            String arr0[]=topicAnswer.split(",");
            //标志选对的个数
            int flag=0;
            //分数
            double score = map2.get(5).get(j).getChooseScore();
            if (j < map.get("5").size()) {
                //学生答案
                a = map.get("5").get(j) + "";
                a = a.substring(1, a.length() - 1);
                String arr[] = a.split(",");
                a = "";
                for (int v = 0; v < arr.length; v++) {
                    if ("1".equals(arr[v]) || " 1".equals(arr[v])) {
                        arr[v] = "A";
                    } else if ("2".equals(arr[v]) || " 2".equals(arr[v])) {
                        arr[v] = "B";
                    } else if ("3".equals(arr[v]) || " 3".equals(arr[v])) {
                        arr[v] = "C";
                    } else if ("4".equals(arr[v]) || " 4".equals(arr[v])) {
                        arr[v] = "D";
                    }
                    if (v <= arr.length-2) {
                        a += arr[v] + ",";
                    } else {
                        a += arr[v];
                    }
                }
                //再进行分割
                String arr2[] = a.split(",");
                for (int q=0;q<arr2.length;q++){
                    for (int i=0;i<arr0.length;i++){
                        if (arr2[q].equals(arr0[i])){
                            //选对1个
                            flag+=1;
                        }
                    }
                    if(flag!=(q+1)){
                        //选错1个即 整题全错
                        flag=0;
                        break;
                    }
                }
                s2=score/arr0.length*flag;
            }
            //存入
            Answer answer = new Answer();
            answer.setUserId(userId);
            answer.setExamId(examId);
            answer.setTopicId(topicId);
            answer.setSocre(s2);
            answer.setAnswerContent(a);
            asi.addAnswer(answer);
        }

        //判断题1
        for (int j = 0; j < map1.get(1).size(); j++) {
            double s3 = 0.0;
            //题目编号
            String topicId = map1.get(1).get(j).getTopicId();
            //正确答案
            String topicAnswer = map1.get(1).get(j).getTopicAnswer();
            //分数
            double score = map1.get(1).get(j).getTopicScore();
            //学生答案
            String a = null;
            if (j < map.get("1").size()) {
                a = map.get("1").get(j) + "";
                if ("1".equals(a)) {
                    a = "T";
                } else if ("2".equals(a)) {
                    a = "F";
                }
                if (topicAnswer.equals(a)) {
                    s3 = score;
                    s += s3;
                }
            }
            //存入
            Answer answer = new Answer();
            answer.setUserId(userId);
            answer.setExamId(examId);
            answer.setTopicId(topicId);
            answer.setSocre(s3);
            answer.setAnswerContent(a);
            asi.addAnswer(answer);
        }

        //填空题2
        for (int j = 0; j < map1.get(2).size(); j++) {
            double s4 = 0.0;
            String a = null;
            //题目编号
            String topicId = map1.get(2).get(j).getTopicId();
            //正确答案
            String topicAnswer = map1.get(2).get(j).getTopicAnswer();
            if (j < map.get("2").size()) {
                //学生答案
                a = map.get("2").get(j) + "";
                a = a.substring(1, a.length() - 1);
                String arr1[] = a.split(",");
                String arr2[] = topicAnswer.split(",");
                //分数
                double score = map1.get(2).get(j).getTopicScore();
                //每个空格的分数
                double score1 = score / arr2.length;

                for (int i = 0; i < arr2.length; i++) {
                    if (i > arr1.length - 1) {
                        break;
                    } else {
                        //去前后空格再比较
                        if (arr2[i].trim().equals(arr1[i].trim())) {
                            //单题分数
                            s4 += score1;
                            //客观题分数
                            s += score1;
                        }
                    }
                }
            }
            //存入
            Answer answer = new Answer();
            answer.setUserId(userId);
            answer.setExamId(examId);
            answer.setTopicId(topicId);
            answer.setSocre(s4);
            answer.setAnswerContent(a);
            asi.addAnswer(answer);
        }

        //综合题3
        for (int j = 0; j < map1.get(3).size(); j++) {
            double s4 = 0.0;
            //学生答案
            String a=null;
            //题目编号
            String topicId = map1.get(3).get(j).getTopicId();
            if (j<map.get("3").size()){
                a = map.get("3").get(j) + "";
            }
            //存入
            Answer answer = new Answer();
            answer.setUserId(userId);
            answer.setExamId(examId);
            answer.setTopicId(topicId);
            answer.setAnswerContent(a);
            asi.addAnswer(answer);
        }

        //把客观成绩、上交时间存入
        Score score = ssi.getScoresByExamIdAndUerId(examId, userId);
        score.setSubmitTime(new Date());
        score.setTotalScore(s);

        int n = ssi.updScore1(score);
        String msg = "提交成功！";
        int code = 200;
        if (n == 0) {
            code = 500;
            msg = "提交失败！";
        }
        AjaxResponse ajaxResponse = new AjaxResponse(msg, code);
        return ajaxResponse;
    }
}
